﻿Namespace EyeOpen.Diagnostics

	Public Class ShellProcess
		Public Sub Execute(ByVal action As Action(Of String), ByVal endAction As Action, ByVal ParamArray commands() As ShellCommand)
			Dim processStart = Sub()
								   Using cmdProcess = New Process()
									   Dim startInfo = New ProcessStartInfo With {.FileName = Environment.GetEnvironmentVariable("COMSPEC"), .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardInput = True, .RedirectStandardOutput = True}
									   cmdProcess.StartInfo = startInfo
									   cmdProcess.Start()
									   Using writer = cmdProcess.StandardInput
										   writer.AutoFlush = True
										   For Each command As ShellCommand In commands
											   writer.WriteLine(String.Format("{0} {1}", command.Name, command.Parameter))
										   Next command
										   writer.Close()
										   While ((Not cmdProcess.StandardOutput.EndOfStream))
											   action(cmdProcess.StandardOutput.ReadLine())
										   End While
										   If endAction IsNot Nothing Then
											   endAction()
										   End If
									   End Using
								   End Using
							   End Sub

			CType(New AsyncWorker(), AsyncWorker).RunWorkerAsync(commands, processStart)
		End Sub
	End Class
End Namespace